const path = require("path");
const glob = require("glob");
const fse = require("fs-extra");

const input = ["projects/noname", "projects/noname/**", []];

const onlyUse = [];

const filterExt = [".bak", ".md"];

const dirFormat = (dir) =>
	path.isAbsolute(dir) ? dir : path.resolve(__dirname, "../", dir);

const dir = dirFormat(input[1]);
const baseDir = dirFormat(input[0]);

const template = (list) => `use nickel::{MediaType, Nickel};
use crate::helper::RenderFile;

pub fn init(server: &mut Nickel) {
	${list.join("\r\n	")}
}
`;

const extlist = [];

glob(dir, function (err, files) {
	if (err) {
		throw err;
	}

	const list = [];

	files.forEach((file) => {
		const code = genCode(file);

		if (code) {
			if (Array.isArray(code)) {
				code.forEach((v) => list.push(v));
			} else {
				list.push(code);
			}
		}
	});

	const result = template(list);

	const src = dirFormat("src/source.rs");

	// const extSet = new Set(extlist);

	// console.log(extSet);

	fse.ensureFileSync(src);

	fse.writeFileSync(src, result);
});

function genCode(file) {
	const ext = path.extname(file);
	const name = path.basename(file);
	const relp = file.slice(baseDir.length);

	extlist.push(ext);

	if (onlyUse.length > 0 && !onlyUse.includes(name)) {
		return null;
	}

	if (filterExt.length > 0 && filterExt.includes(ext)) {
		return null;
	}

	if (name === "welcome.txt") {
		return `println!("{}", include_str!("${file}"));`;
	}

	if (name === "index.html") {
		return `server.render_html("/", include_str!("${file}"));`;
	}

	if (ext === ".js") {
		return `server.render_js("${relp}", include_str!("${file}"));`;
	}

	if (ext === ".html") {
		return [
			`server.render_html("${relp}", include_str!("${file}"));`,
			`server.render_html("${relp.slice(0, -5)}", include_str!("${file}"));`,
		];
	}

	if (ext === ".css") {
		return `server.render_css("${relp}", include_str!("${file}"));`;
	}

	if (ext === ".png") {
		return `server.render_png("${relp}", include_bytes!("${file}"));`;
	}

	if (ext === ".jpg" || ext === ".jpeg") {
		return `server.render_jpeg("${relp}", include_bytes!("${file}"));`;
	}

	if (ext === ".mp3") {
		return `server.render_bytes("${relp}", include_bytes!("${file}"), MediaType::Mpeg);`;
	}

	if (ext === ".mp3") {
		return `server.render_bytes("${relp}", include_bytes!("${file}"), MediaType::Mpeg);`;
	}

	if (ext.length > 2) {
		const ident = ext.slice(1, 2).toUpperCase() + ext.slice(2);
		return `server.render_bytes("${relp}", include_bytes!("${file}"), MediaType::${ident});`;
	}

	return null;
}
